package ru.arriah.servicedesk.web.dispatcher.action;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.ClientBean;
import ru.arriah.servicedesk.bean.DepartmentBean;
import ru.arriah.servicedesk.bean.GroupBean;
import ru.arriah.servicedesk.bean.OrganizationBean;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.bean.RequestTypeBean;
import ru.arriah.servicedesk.bean.error.RequestFormErrorBean;
import ru.arriah.servicedesk.ejb.ClientManagerLocalHome;
import ru.arriah.servicedesk.ejb.ClientManagerLocalObject;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalObject;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalHome;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalObject;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;


public class CancelRequestAction extends DumbAction {
  protected RequestFormErrorBean requestFormErrorBean;  
  protected RequestManagerLocalHome requestManagerHome;
  protected EmployeeManagerLocalHome employeeManagerHome;
  protected OrganizationManagerLocalHome organizationManagerHome;
  protected ClientManagerLocalHome clientManagerHome;
  protected GroupManagerLocalHome groupManagerHome;

   public CancelRequestAction() throws NamingException {
     super();

     requestManagerHome = 
        Utils.getRequestManagerHomeInterface();
     organizationManagerHome = 
        Utils.getOrganizationManagerHomeInterface();
     clientManagerHome = 
       Utils.getClientManagerHomeInterface();
     groupManagerHome = 
       Utils.getGroupManagerHomeInterface();
     employeeManagerHome = 
       Utils.getEmployeeManagerHomeInterface();
   }
   
   
   /**
    * Request validation
    * @param requestBean
    * @return
    */
   private boolean isValid(RequestBean requestBean) {
     requestFormErrorBean = new RequestFormErrorBean();
     boolean result = true;   

     if (requestBean.getComment() == null || requestBean.getComment().equals("")) {
       requestFormErrorBean.setComment(
         config.getProperty("ERROR.REQUESTFORM.COMMENT")
       );
       result = false;
     }     

     return result;
   }

   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
     try {       
              
       RequestManagerLocalObject requestManager = 
         requestManagerHome.create();
                           
       int userId = 
         Utils.getUserId(request);
       int requestId = idVal(request.getParameter("id"));
       
       RequestBean requestBean = new RequestBean();
       
       /* Get parameters from request */
       requestBean.setId(requestId);
       requestBean.setClientText(request.getParameter("text"));
       requestBean.setDispatcherText(request.getParameter("dispatcherText"));

       //TODO replace to actual organization id
       requestBean.setOrganizationId(1);
       requestBean.setDepartmentId(idVal(request.getParameter("department_id")));
       requestBean.setClientId(idVal(request.getParameter("client_id")));

       requestBean.setGroupId(idVal(request.getParameter("group_id")));
       requestBean.setRequestTypeId(idVal(request.getParameter("requesttype_id")));
       requestBean.setRegistrationDate(new Date());
       requestBean.setRegNumber(request.getParameter("regNumber"));
       requestBean.setRoom(request.getParameter("room"));
       requestBean.setComment(
         request.getParameter("comment")
       );             
       
       
       /* Request not valid */       
       if (!this.isValid(requestBean)) {
         OrganizationManagerLocalObject organizationManager = 
           organizationManagerHome.create();
         ClientManagerLocalObject clientManager = clientManagerHome.create();
         GroupManagerLocalObject groupManager = groupManagerHome.create();

         Collection<DepartmentBean> departmentsList = 
           organizationManager.selectDepartments(requestBean.getOrganizationId());

         Collection<OrganizationBean> organizationsList = 
           organizationManager.selectOrganizations();

         Collection<ClientBean> clientsList = 
           clientManager.selectClientsByDepartment(requestBean.getDepartmentId());

         Collection<RequestTypeBean> requestTypesList = 
           requestManager.selectRequestTypes();

         Collection<GroupBean> groupsList = groupManager.selectGroups();

         organizationManager.remove();
         clientManager.remove();
         requestManager.remove();
         groupManager.remove();         

         request.setAttribute("groupsList", groupsList);
         request.setAttribute("requestTypesList", requestTypesList);
         request.setAttribute("organizationsList", organizationsList);
         request.setAttribute("clientsList", clientsList);
         request.setAttribute("departmentsList", departmentsList);
         request.setAttribute("requestBean", requestBean);
         request.setAttribute("error", requestFormErrorBean);
         addErrorMessage(request, config.getProperty("ERROR.REQUESTFORM_FIELDS_INVALID"));                  
         return actionMapping.getFailureTarget();
       }
       
       /* Request is valid, try to cancel it */
       if (requestManager.cancelRequestByDispatcher(requestBean, userId))        
          addInfMessage(request, config.getProperty("INF.REQUEST_CANCELED"));       
       else 
          addErrorMessage(request, config.getProperty("ERROR.REQUEST_NOT_CANCELED"));
       
       requestManager.remove();                     
                          
       return actionMapping.getSuccessTarget();
    } catch (Exception e) {
       handleException(e, "execute");
       throw new InternalException("ErrorMessage.internal");
    }
   }
}